<!--移动端-提现-->
<template>
  <div>
    <!--  我的余额-->
    <el-row>
      <el-col :span="24">
        <el-card shadow="never" class="card">
          <el-row class="top">
            <el-col :span="24">
              <div class="withdrawable-title">可提现余额(元)</div>
              <div class="withdrawable-money">￥ {{ incomeTotal.earnAmount }} <span style="font-size: 10px">元</span>
              </div>
            </el-col>
          </el-row>
          <el-row class="bottom">
            <el-col :span="12" class="income">累计收益： {{ incomeTotal.allEarnAmount }}元</el-col>
            <el-col :span="12" class="income">已提现余额： {{ incomeTotal.withdrawAmount }}元</el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <!--    输入参数-->
    <el-tabs
        v-model="state.activeName"
        type="card"
        class="tabs"
        @tab-click="handleClick"
    >
      <el-tab-pane label="我要提现" name="withdraw">
        <el-card  shadow="never">
          <el-form
              ref="withdrawRuleFormRef"
              label-position="top"
              :rules="withdrawRules"
              :model="withdrawRuleForm"
              label-width="auto"
              style="max-width: 500px"
          >
            <el-form-item label="提取金额（元）：" prop="withdrawAmount">
              <el-row :gutter="20">
                <el-col :span="22">
                  <el-input-number v-model="withdrawRuleForm.withdrawAmount" :min="0.01" :max="2000" :precision="2"/>
                </el-col>
                <el-col :span="2">
                  <el-button type="primary" link @click="allWithdraw">全部提现</el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="姓名：" prop="accountName">
              <el-input v-model="withdrawRuleForm.accountName" maxlength="4" show-word-limit
                        placeholder="请输入您的姓名"/>
            </el-form-item>
            <el-form-item label="手机号：" prop="accountPhone">
              <el-input v-model="withdrawRuleForm.accountPhone" maxlength="11" show-word-limit
                        placeholder="请输入您的手机号"/>
            </el-form-item>
            <el-form-item label="身份证号：" prop="idCardNo">
              <el-input v-model.number="withdrawRuleForm.idCardNo" maxlength="18" show-word-limit
                        placeholder="请输入您的身份证号"/>
            </el-form-item>
            <el-form-item label="支付宝账号：" prop="accountNumber">
              <el-input v-model="withdrawRuleForm.accountNumber" maxlength="20" show-word-limit
                        placeholder="请输入您的支付宝账号"/>
            </el-form-item>
            <el-form-item>
              <el-button class="btn" type="primary" @click="goWithdraw(withdrawRuleFormRef)">提交 提现</el-button>
            </el-form-item>

          </el-form>
        </el-card>

      </el-tab-pane>
      <el-tab-pane label="提现记录" name="withdrawList">
        <el-empty v-if="state.withdrawList.length === 0" description="您还没有提现记录"/>
        <el-card shadow="never" v-for="item in state.withdrawList">
          <p class="text item">提现编号 {{ item.businessCode }}</p>
          <p class="text item">提现金额 {{ item.withdrawAmount }}</p>
          <p class="text item">提现状态 {{ item.statusText }}</p>
          <p class="text item">提现时间 {{ item.withdrawTime }}</p>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
        v-model="state.dialogVisible"
        title="提现提示"
        width="80%"
    >
      <span>每月 10号 9:00-23:00 为提现日</span>
    </el-dialog>
    <!--    提交-->
  </div>
</template>
<script setup lang="ts">
//增加SEO


useHead({
  title: '提现 - 迅颖',
  meta: [
    {hid: 'keywords', name: 'keywords', content: '提现'}
  ]
})

import requester from "~/utils/request";
import type {TabsPaneContext} from 'element-plus'
import type {FormRules, FormInstance} from 'element-plus'
import {useRoute, useRouter} from "vue-router";
import {userStore} from "~/composables/useUserStore";
const route = useRoute()
const router = useRouter()
const store = userStore()
const withdrawRuleFormRef = ref<FormInstance>()
// 收益总览
const incomeTotal = reactive({
  allEarnAmount: 0.00,
  earnAmount: 0.00,
  withdrawAmount: 0.00
});

const state = reactive(<any>{
  fullscreenLoading: false,
  dialogVisible: false,
  activeName: "withdraw",
  withdrawList: [],
  withdrawPage: {
    pageValidate: {
      pageNo: 1,
      pageSize: 10
    },
    userCode: ""
  },
})

// 监听store中的isLogin状态,如果新值为true说明已经登录成功
watch(() => store.isLogin, (newValue) => {
  if (newValue) {
    accountInfo()
  }
})

interface withdrawRuleForm {
  userCode: string,
  accountName: string,
  accountPhone: string,
  idCardNo: string,
  accountNumber: string,
  withdrawAmount: number,
}

const withdrawRuleForm = reactive<withdrawRuleForm>({
  userCode: store.token.userCode,
  accountName: "",
  accountPhone: "",
  idCardNo: "",
  accountNumber: "",
  withdrawAmount: 0.00,
})


//验证手机哈
const validatePhoneNumber = (rule: any, value: string, callback: any) => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!value) {
    callback(new Error('手机号不能为空'));
  } else if (!phoneRegex.test(value)) {
    callback(new Error('请输入正确的中国大陆手机号'));
  } else {
    callback();
  }
};
const validateIDCard = (rule: any, value: string, callback: any) => {
  const idCardRegex = /^(^[1-9]\d{5}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$)|(^[1-9]\d{7}(0[1-9]|[12]\d|3[01])\d{2}(\d|X|x)$)$/;
  if (!value) {
    callback(new Error('身份证号不能为空'));
  } else if (!idCardRegex.test(value)) {
    callback(new Error('请输入正确的中国身份证号'));
  } else {
    callback();
  }
};
const validateChineseName = (rule: any, value: string, callback: any) => {
  const nameRegex = /^[\u4e00-\u9fa5]{2,4}$/;
  if (!value) {
    callback(new Error('姓名不能为空'));
  } else if (!nameRegex.test(value)) {
    callback(new Error('请输入正确的中文姓名（2-4个汉字）'));
  } else {
    callback();
  }
};
//提现验证
const withdrawRules = reactive<FormRules<withdrawRuleForm>>({
  withdrawAmount: [
    {required: true, message: '提现金额不能为空', trigger: 'blur'}
  ],
  accountName: [
    {required: true, message: '姓名不能为空', trigger: 'blur'},
    {validator: validateChineseName, trigger: 'blur'}
  ],
  accountPhone: [
    {required: true, message: '手机号不能为空', trigger: 'blur'},
    {validator: validatePhoneNumber, trigger: 'blur'}
  ],
  idCardNo: [
    {required: true, message: '身份证号不能为空', trigger: 'blur'},
    {validator: validateIDCard, trigger: 'blur'}
  ],
  accountNumber: [
    {required: true, message: '支付宝账号不能为空', trigger: 'blur'}
  ],
})

//全部提现回显
function allWithdraw() {
  requester.post("/api/account/getAccount", {"userCode": store.token.userCode}).then(res => {
    withdrawRuleForm.withdrawAmount = Number(res.data.earnAmount)
  })
}

//提现操作
const goWithdraw = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      withdrawRuleForm.userCode = store.token.userCode
      requester.post("/api/withdraw/doWithdraw", withdrawRuleForm).then((res:any) => {
        if (res.code === 200) {
          router.push(`projectAddSuccess`)
        }
        if (res.code === 300) {
          ElMessage.warning("警告：" + res.msg)
          return
        }
      })
    }
  })
}
const silentLogin = async (code: any) => {
  //code换取登录信息
  const response:any = await requester.post('/api/login/codeLogin', {code: code, type: "snsapi_base"})
  //40029code被使用
  if (response.code === 200) {
    //返回数据中有 token
    store.setToken(response.data)
    store.setIsLogin(true)
  } else {
    getCode()
  }
}

onMounted(async () => {
  // 判断用户是否登录
  if (store.isLogin) {
    accountInfo()
  } else {
    const code = route.query.code
    if (code === undefined) {
      getCode()
    } else {
      silentLogin(code)
    }
  }
  state.dialogVisible = true
})

function getCode() {
  //拼接链接进行登录
  window.location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4754a2bb841ba595&redirect_uri=` +
      encodeURIComponent("https://xunyingcloud.cn/my/mobile/withdraw") +
      "&response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect")
}


//查询用户账户明细
function accountInfo() {
  requester.post("/api/account/getAccount", {"userCode": store.token.userCode}).then(res => {
    incomeTotal.allEarnAmount = res.data.allEarnAmount
    incomeTotal.earnAmount = res.data.earnAmount
    incomeTotal.withdrawAmount = res.data.withdrawAmount
  })
}


/**
 * 标签页
 * @param tab
 * @param event
 */
const handleClick = (tab: TabsPaneContext, event: Event) => {
  if (tab.props.name === 'withdrawList') {
    accountInfo()
    state.withdrawPage.userCode = store.token.userCode
    requester.post("/api/withdraw/myWithdrawList", state.withdrawPage).then(res => {
      state.withdrawList = res.data.lists
    })
  }
}

</script>
<style scoped lang="scss">
.card {
  width: 100%;
  height: 100px;
  background: linear-gradient(to bottom, #e09d9f, #d9b9cc);
  color: #f3eeee;

  .top {
    height: 80%;

    .withdrawable-title {
      font-size: 12px;
    }

    .withdrawable-money {
      padding-top: 5px;
      font-size: 22px;
    }
  }

  .bottom {
    padding-top: 5px;
    height: 20%;

    .income {
      font-size: 11px;
    }
  }
}

.tabs {
  padding-top: 5px;
}

:deep(.el-tabs__item.is-active, .el-tabs__item:hover) {
  color: #dc9bae;
}

.btn {
  display: block;
  margin: 0 auto;
  width: 65%;
  background: linear-gradient(to bottom, #e09d9f, #d9b9cc);
}

:deep(.el-button--primary) {
  --el-button-border-color: white;
}
</style>
